
import { devApi as api } from "@/api";
import { Col, Form, Input, Modal, Row, Spin, message, Tabs, Space, Button, Select, Checkbox } from "antd";
import React, { useState, useEffect, useImperativeHandle, } from "react";
import ProEditTableComponent from "./ProEditTableComponent";
import CodePreview from "./component/codePreviewTree";

const EditForm = ({ onRef, getList = Function }) => {
    const [codeObj, setCodeObj] = useState({});
    const [editType, setEditType] = useState("add");
    const [show, setShow] = useState(false);
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();
    const [dataSource, setDataSource] = useState([]);

    /**@description 取消 */
    const onCanle = () => {
        setShow(false);
        setDataSource([]);
        form.resetFields();
    }

    /**@description 添加|修改操作 */
    const open = async ({ type = "add", record = Object }) => {
        const { id = undefined } = record;
        setShow(true);
        form.resetFields();
        form.setFieldValue("type", "action." + type)
        setEditType(type);



        if (type === "update") {
            if (id) {
                try {
                    setLoading(true);
                    const { data, code, msg } = await api.getDetail(id);
                    if (code === 0) {
                        setCodeObj(data.object)
                    }
                    form.setFieldsValue({
                        type: type || undefined,
                        ...data
                    });
                    const { modelData = [] } = data;
                    setDataSource(modelData)
                } catch (error) {
                    message.error(error)
                } finally {
                    setLoading(false);
                }
            }
        } else {
        }


    }

    const disparseTrueOrFalse = (val) => {
        // if (val === "" || val === undefined || val === "false" || val == null) {
        //     return false
        // } else {
        //     return true
        // }
        if (val === "" || val == null || val === undefined) {
            return val;
        }
        if (val === "true") {
            return true;
        }
        if (val === "false") {
            return false
        }
    }



    /**@description 异步保存数据 */
    const saveDataToServer = async (object) => {
        console.log("保存配置", object);
        console.log("模型数据：", dataSource);
        let params = {
            ...object,
            modelData: dataSource
            // modelData: dataSource.map((row, index) => ({
            //     ...row,
            //     // edit: row.edit === 'true' ? true : false,
            //     // show: row.show === 'true' ? true : false,
            //     // search: row.search === 'true' ? true : false,
            //     // index: row.index === 'true' ? true : false,
            //     // require: row.require === 'true' ? true : false,
            //     // unique: row.unique === 'true' ? true : false,
            //     edit: disparseTrueOrFalse(row.edit),
            //     show: disparseTrueOrFalse(row.show),
            //     search: disparseTrueOrFalse(row.search),
            //     index: disparseTrueOrFalse(row.index),
            //     require: disparseTrueOrFalse(row.require),
            //     unique: disparseTrueOrFalse(row.unique),
            // }))
        }
        try {
            const res = await api.saveData(params);
            getList();
            onCanle();
        } catch (error) {

        } finally {

        }

    }

    /**@description 校验表单 */
    const validateForm = async () => {
        form.validateFields().then(res => {
            saveDataToServer(res)
        })
    }

    /**@description 向外暴露方法 */
    useImperativeHandle(onRef, () => ({
        open
    }))

    /**@description form表单props配置 */
    const formProps = {
        form,
        initData: {
            type: undefined,
            parentId: "0",
            menuType: "1"
        }
    }

    useEffect(() => {
        !show && form.resetFields()
    }, [show])


    const onChange = (key) => {
        console.log(key);
    };



    const BaseSettingComponent = () => {
        return (
            <>
                <Row gutter={24}>
                    <Col span={24} style={{ display: "none" }} >
                        <Form.Item label="id" name="id">
                            <Input />
                        </Form.Item>
                    </Col>

                    <Col span={12}>
                        <Form.Item label="页面名称" name="title">
                            <Input placeholder="请输入页面名称" />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="组件名称" name="componentName">
                            <Input placeholder="请输入组件名，大写字母开头，示例：BannerListView" />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item label='备注' name="remark">
                            <Input.TextArea />
                        </Form.Item>
                    </Col>
                    <Col span={24}>
                        <Form.Item
                            rules={[
                                {
                                    required: true,
                                    message: '表名不能为空'
                                },
                                {
                                    pattern: /^[A-Za-z_]+$/,
                                    message: '只能包含字母和下划线'
                                }
                            ]}
                            label='数据表名' name="tableName">
                            <Input />
                        </Form.Item>
                    </Col>
                </Row>
            </>
        )
    }

    const disparse = (val) => {
        if (val === undefined || val == null || val == "") {
            return val;
        }
        if (val == false) {
            return "false"
        } else {
            return "true"
        }
    }


    const items = [
        {
            key: '12',
            label: '基本配置',
            children: <BaseSettingComponent />,
        },
        {
            key: '2',
            label: '模型配置',
            children: <ProEditTableComponent dataSource={dataSource} setDataSource={setDataSource} />
        },
        editType === "update" && {
            key: "3",
            label: "代码预览",
            children: <CodePreview codeObj={codeObj} />,
        }

    ].filter(Boolean);

    return (
        <>
            <Modal
                title="模型配置"
                width={1200}
                open={show}
                centered={true}
                destroyOnClose={true}
                onCancel={onCanle}
                onOk={validateForm}
                styles={{
                    header: {},
                    body: {
                        height: 500,
                    }
                }}
            >
                <Spin spinning={loading}>
                    <Form
                        // {...formItemLayout}
                        {...formProps}
                    >
                        <Tabs defaultActiveKey="1" items={items} onChange={onChange} />
                    </Form>
                </Spin>

            </Modal>
        </>
    )
}
export default EditForm;